# plugs/gcollect.py
#
#

""" run garbage collector """

__status__ = "seen"

from gozerbot.periodical import periodical
from gozerbot.generic import rlog
from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.persist.persiststate import PlugState
from gozerbot.plughelp import plughelp
from gozerbot.tests import tests

## basic imports

import gc
import time

## plughelp

plughelp.add('gcollect', 'help the garbage collector')

## defines

state = PlugState()
state.define('wait', 300)
state.define('enable', 0)

pid = None

## init funcion

def init():
    if state['enable']: 
        gc.enable()
        rlog(10, 'gcollect', 'garbage collector enabled .. wait is %s' % state['wait'])
        global pid
        pid = periodical.addjob(state['wait'], 0, gcollect)

## shutdown function

def shutdown():
    periodical.kill()

## gcollect function

def gcollect():
    rlog(1, 'gcollect', 'running collector')
    gc.collect()
    time.sleep(5)
    gc.collect()
    time.sleep(5)
    gc.collect()


## gcollect-wait command

def handle_gcollectwait(bot, ievent):
    """ change the interval on which gcollect is run. """
    try: newwait = int(ievent.args[0])
    except (IndexError, ValueError): ievent.reply('gcollect wait is %s seconds' % state['wait']) ; return
    if newwait < 60: ievent.reply('min. number of seconds is 60') ; return
    state['wait'] = newwait
    state.save()
    global pid
    if pid: periodical.changeinterval(pid, newwait)
    ievent.reply('gcollect wait set to %s' % state['wait'])

cmnds.add('gcollect-wait', handle_gcollectwait, 'OPER')
examples.add('gcollect-wait', 'set wait of garbage collector', 'gcollect-wait 300')
tests.add('gcollect-wait 300')

## gcollect command

def handle_gcollect(bot, ievent):
    """ do a collector run. """
    gcollect()
    ievent.reply('collector runned')

cmnds.add('gcollect', handle_gcollect, 'OPER', threaded=True)
examples.add('gcollect', 'run garbage collector', 'gcollect')
tests.add('gcollect')

## gcollect-enable command

def handle_gcollectenable(bot, ievent):
    """ enable gcollect. """
    global pid
    state['enable'] = 1
    state.save()
    global pid
    pid = periodical.addjob(state['wait'], 0, gcollect)
    ievent.reply('gcollect enabled')

cmnds.add('gcollect-enable', handle_gcollectenable, 'OPER')
examples.add('gcollect-enable', 'enable the garbage collector', 'gcollect-enable')
tests.add('gcollect-enable')

## gcollect-disable command

def handle_gcollectdisable(bot, ievent):
    """ disable gcollect. """
    state['enable'] = 0
    state.save()
    periodical.kill()
    ievent.reply('gcollect disabled')

cmnds.add('gcollect-disable', handle_gcollectdisable, 'OPER')
examples.add('gcollect-disable', 'disable the garbage collector', 'gcollect-disable')
tests.add('gcollect-disable')

#### BHJTW 22-01-2012
